package org.jeecg.common.datasource.config;

import com.zaxxer.hikari.HikariDataSource;
import org.jeecg.common.COSMOS;
import org.jeecg.common.datasource.utils.DBFUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Iterator;
import java.util.Map;

@AutoConfigureAfter({DataSourceConfig.class})
@Configuration
public class DataSourceBean {
    private static final Logger LG = LoggerFactory.getLogger(DataSourceBean.class);

    @Resource
    private DataSourceConfig dataSourceConfig;

    @Bean(name = {"dataSource"})
    public DataSource dataSource(){
        Map<String, HikariDataSource> dataSourceConfigMap = this.dataSourceConfig.getDbList();
        if(dataSourceConfigMap.isEmpty()){
            throw new RuntimeException("【数据库】请检查数据源配置。");
        }

        // 默认节点数据源
        HikariDataSource selectDefaultDB = null;
        Iterator<String> dbNames = dataSourceConfigMap.keySet().iterator();
        while(dbNames.hasNext()){
            String dbName = dbNames.next();
            if(dbName.equals(dataSourceConfig.getDefaultName())){
                selectDefaultDB = dataSourceConfigMap.get(dbName);
            }
        }

        LG.info("【数据库】默认数据源：{}",  selectDefaultDB);
        if(selectDefaultDB == null){
            throw new RuntimeException("【数据库】缺少默认数据源配置。");
        }

        String dbType = DBFUtil.getDbType(selectDefaultDB.getDriverClassName());
        // 默认数据源数据库类型
        COSMOS.DB_TYPE = dbType;
        return selectDefaultDB;
    }

}
